package com.tube.fiddles.support.spring.ext;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.tube.fiddles.util.DESUtil;

public class PropertyPlaceholderConfigurerEx extends PropertyPlaceholderConfigurer {

    public final static String CONN_USERNAME_KEY = "database.username";
    public final static String CONN_PASSWORD_KEY = "database.password";
    
    private boolean encrypted;
    private String keyOfUsername = CONN_USERNAME_KEY;
    private String keyOfPassword = CONN_PASSWORD_KEY;

    @Override
    protected void processProperties(
            ConfigurableListableBeanFactory beanFactoryToProcess,
            Properties props) throws BeansException {
        if (isEncrypted()) {
            String username = props.getProperty(keyOfUsername);
            String password = props.getProperty(keyOfPassword);
            
            if (null != username && username.length() > 0) {
                // decrypt the username, and set it back
                props.setProperty(keyOfUsername, DESUtil.decrypt(username));
            }
            if (null != password && password.length() > 0) {
                // decrypt the password, and set it back
                props.setProperty(keyOfPassword, DESUtil.decrypt(password));
            }
        }
        super.processProperties(beanFactoryToProcess, props);
    }

    public boolean isEncrypted() {
        return encrypted;
    }

    public void setEncrypted(boolean encrypted) {
        this.encrypted = encrypted;
    }

    public String getKeyOfUsername() {
        return keyOfUsername;
    }

    public void setKeyOfUsername(String keyOfUsername) {
        this.keyOfUsername = keyOfUsername;
    }

    public String getKeyOfPassword() {
        return keyOfPassword;
    }

    public void setKeyOfPassword(String keyOfPassword) {
        this.keyOfPassword = keyOfPassword;
    }
    
}
